import numpy as np
from PIL import Image

def log_color_enhance(
    img_pil,
    alpha=125.0,
    c=1.0,
    gain=1.0,#系数
    bias=0.0, #偏置项
):
    img = np.array(img_pil).astype(np.float32) / 255.0
    denom = np.sum(img, axis=2, keepdims=True) + 1e-6  # 防止除零

    with np.errstate(divide='ignore', invalid='ignore'):
        log_img = np.log(img + 1e-6)
        crf = np.log(alpha * (img / denom) + c)

    enhanced = gain * (log_img * crf) + bias

    # 归一化到0~255 uint8
    enhanced -= np.min(enhanced)
    enhanced /= np.max(enhanced)
    enhanced = (enhanced * 255).astype(np.uint8)
    return Image.fromarray(enhanced)

# 使用示例
if __name__ == "__main__":
    img = Image.open("D:\Retinex\\test\\test.jpg").convert("RGB")
    enhanced_img = log_color_enhance(img, alpha=125.0, c=1.0, gain=1.0, bias=0.0)

    # 显示结果
    import matplotlib.pyplot as plt
    plt.figure(figsize=(8,4))
    plt.subplot(1,2,1)
    plt.imshow(img)
    plt.title("Original")
    plt.axis("off")

    plt.subplot(1,2,2)
    plt.imshow(enhanced_img)
    plt.title("Log + Color Restore")
    plt.axis("off")

    plt.tight_layout()
    plt.show()